import { useState, useEffect, useRef, forwardRef, useImperativeHandle } from 'react'
import { Form as TForm, Input, Button } from 'tdesign-react'
import './index.less'

const { FormItem } = TForm

const Form = forwardRef((props: any, ref: any) => {

  const { formOptions = [], ...extraProps } = props

  const formRef = useRef(null)

  const renderFormItem = (type: string, itemProps: any, label: string) => {
    switch(type) {
      case 'input':
        return <Input placeholder={itemProps.placeholder || `请输入${label}`} />
      default:
        return <Input placeholder='请输入' />
    }
  }

  useImperativeHandle(ref, () => ({ getFormData }))

  const getFormData = () => {
    return formRef.current ? (formRef.current as any).getFieldsValue(true) : {}
  }

  return <div className='aio-form-container'>
    <TForm
      ref={formRef}
      labelAlign='right'
      layout='vertical'
      preventSubmitDefault
      resetType='empty'
      showErrorMessage
      {...extraProps}
    >

      {formOptions.map((formItem: any, index: number) => {
        const { formProps, itemProps, type } = formItem
        const label = formProps.label
        return <FormItem
          {...formProps}
          key={index}
        >
          {renderFormItem(type, itemProps, label)}
        </FormItem>
      })}
    </TForm>
  </div>
})

export default Form
